<!--#
layout("_layout.html",{}){
 #-->
<!--#layout("sidebar.html", {"c_user":obj.topic.author}){} #-->

<div id='content'>
  <div class='panel'>
    <div class='header'>
      <ol class='breadcrumb' vocab="http://schema.org/" typeof="BreadcrumbList">
        <li property="itemListElement" typeof="ListItem">
        	<a data-pjax href='${ctxPath}/yvr/list' property="item" typeof="WebPage"><span property="name">主页</span></a><span class='divider'>/</span>
        </li>
        <li class='active' property="itemListElement" typeof="ListItem" >
        	<a data-pjax href='${ctxPath}/yvr/list/${obj.topic.type}' property="item" typeof="WebPage"><span property="name">${obj.topic.type.display}</span></a>
        	<meta property="position" content="2">
        </li>
      </ol>
    </div>
    <div itemscope itemtype="http://schema.org/NewsArticle">
    <meta itemprop="datePublished" content="${obj.topic.createTime, ISO_8601}"/>
    <div style="display: none;"><img itemprop="image" src="${cdnbase}${ctxPath}/rs/logo/logo.png" alt="NutzCN Logo"/></div>
    <div class='header topic_header'>
      <span class="topic_full_title" itemprop="headline">
        <!--#
		layout("_top_good.html",{"topic":obj.topic}){}
		 #-->
		${obj.topic.title}
      </span>
      <div class="changes">
        <span>
          发布于 ${obj.topic.createAt}
        </span>
        <span>
          作者 <a data-pjax href="${ctxPath}/yvr/u/${obj.topic.author.loginname}">${obj.topic.author.nickname!, escape}</a>
        </span>
        <span>
          ${obj.topic.visitCount} 次浏览
        </span>
        <!--# if (null != obj.current_user!) {  #-->
        <!--
        <span id="watch_btn">
          <a href="#" onclick="watch_me();" title="有新回复时自动刷新页面" data-intro="有新回复时自动刷新页面,这样就不必手动刷新">自动刷新</a>
        </span>
        -->
        <span id="send_to_phone_btn">
          <a href="#" onclick="send_to_phone();" title="瞬间推送到手机客户端" data-intro="瞬间推送到手机客户端,传说中的'瞬移' (我的世界乱入...)">推送到手机</a>
        </span>
        <!--#} #-->
        <span>
          <a id="copy_link_btn" href="#" class="zclip" title="复制标题和地址" data-intro="可以复制标题和地址">复制</a>
        </span>
        <span>
          <a id="copy_link_btn" href="#" class="zclip" title="跨设备免登陆.注意,不是给手机客户端用的" data-intro="手机扫描后可免登陆访问该页面" onclick="cs_qrcode();return false; ">跨屏二维码</a>
        </span>
      </div>
      
      <div class="changes">
      		<span id="TopicTagSpan">
      		标签:</span>
      	<!--# if (null != obj.topic.tags && obj.topic.tags.~size > 0){ #-->
      		<!--#for(_tag in obj.topic.tags) { #-->
      		<a data-pjax href='${ctxPath}/yvr/tag/${_tag}' property="item" typeof="WebPage" class="topic_tag">${_tag}</a>
      		<!--#} #-->
      	<!--#} else { #-->
      		无
      	<!--#} #-->
      </div>
      <!--# if (shiro.hasPermit("topic:update")) {  #-->
      <div id="manage_topic">
         <a href='#' onclick="topic_update('${obj.topic.id}', ${!obj.topic.top}, 'top');">
            <!--# if (obj.topic.top) {  #-->
              <i class="fa fa-lg fa-star-o" title='取消置顶'></i>
            <!--# } else {  #-->
              <i class="fa fa-lg fa-star" title='置顶'/></i>
            <!--# }  #-->
          </a>
          
          <a href='#' onclick="topic_update('${obj.topic.id}', ${!obj.topic.good}, 'good');">
            <!--# if (obj.topic.good) {  #-->
              <i class="fa fa-lg fa-heart-o" title="取消精华"></i>
            <!--# } else {  #-->
              <i class="fa fa-lg fa-heart" title="加精华"></i>
            <!--# }  #-->
          </a>

          <a href='#' onclick="topic_update('${obj.topic.id}', ${!obj.topic.lock}, 'lock');">
            <!--# if (obj.topic.lock) {  #-->
              <i class="fa fa-lg fa-unlock" title='取消锁定'></i>
            <!--# } else {  #-->
              <i class="fa fa-lg fa-lock" title='锁定(不可再回复)'/></i>
            <!--# }  #-->
          </a>
      </div>
      <!--# }  #-->
    </div>
    <div class='inner topic'>

      <div class='topic_content' itemprop="articleBody">
        <div class="markdown-text">
        ${markdown(obj.topic.content)}
		</div>
      </div>
    </div>
    </div>
  </div>
  <!--# if ( null != obj.topic.replies!) {  #-->
  <div class='panel'>
    <div class='header'>
      <span class='col_fade'>${obj.topic.replies.~size} 回复</span>
    </div>
    <!--#
    var _i = 0;
    for (reply in obj.topic.replies) {
    	layout("_reply.html", {"reply":reply, "indexInCollection":_i}){};
    	_i = _i + 1;
    }
     #-->
  </div>
  <!--# }  #-->
  <div class='panel' data-intro="回帖回帖回帖!!" data-position="top">
    <div class='header'>
      <span class='col_fade'>添加回复</span>
    </div>
    <div class='inner reply'>
    <!--# if (obj.topic.lock) { #-->
    	<span class='col_fade'>该帖子已被锁定,不能回复.</span>
    <!--# } else if (null != obj.current_user!){  #-->
      <form id='reply_form' action='#'>

        <div class='markdown_editor in_editor'>
          <div class='markdown_in_editor'>
            <textarea class='editor' name='content' rows='8'></textarea>

            <div class='editor_buttons'>
              <input class='span-primary submit_btn' type="submit" data-loading-text="回复中.." value="回复${obj.topic.lock ? '(此主题已锁定)' : ''}" ${obj.topic.lock ? 'disabled="disabled"' : ''}>
            </div>
          </div>

        </div>

        <input type='hidden' name='_csrf' id="_csrf" value='${obj._csrf!}'/>
      </form>
    <!--# } else { #-->
    	<span class='col_fade' data-intro="登陆是回帖的必要且充分条件,推荐使用github登陆">请先登陆</span>
    <!--# }  #-->
    </div>
  </div>
</div>

<div class="replies_history">
  <div class="inner_content"></div>
  <div class="anchor"></div>
</div>
<!--# if (null != obj.current_user!){  #-->
<script src="${cdnbase}${base}/rs/libs/markdownit.js?v=1"></script>
<script src="${cdnbase}${base}/rs/libs/code-prettify/prettify.js?v=1"></script>
<script src="${cdnbase}${base}/rs/libs/editor/editor.js?v=3"></script>
<script src="${base}/rs/libs/editor/ext.js?v=5"></script>
<script>
  $(document).ready(function () {
    // 获取所有回复者name
    var allNames = $('.reply_author').map(function (idx, ele) {
      var _tmp = $(ele).text().trim();
      if (_tmp.indexOf("(") > -1 && _tmp.indexOf(")") > _tmp.indexOf("(")){
          return _tmp.substr(_tmp.indexOf("(")+1, _tmp.indexOf(")") - _tmp.indexOf("(") - 1);
      }
      return _tmp;
    }).toArray();
    allNames = _.uniq(allNames);
    // END 获取所有回复者name
    // 编辑器相关
    $('textarea.editor').each(function(){
      var editor = new Editor({
        status: []
      });
      var $el = $(this);
      editor.render(this);
      //绑定editor
      $(this).data('editor', editor);
      var $input = $(editor.codemirror.display.input);
      $input.keydown(function(event){
        if (event.keyCode === 13 && (event.ctrlKey || event.metaKey)) {
          event.preventDefault();
          if (console)
          	console.log("hi");
          //$el.closest('form').submit();
        }
      });
      // at.js 配置
      var codeMirrorGoLineUp = CodeMirror.commands.goLineUp;
      var codeMirrorGoLineDown = CodeMirror.commands.goLineDown;
      var codeMirrorNewlineAndIndent = CodeMirror.commands.newlineAndIndent;
      $input.atwho({
        at: '@',
        data: allNames
      })
      .on('shown.atwho', function () {
        CodeMirror.commands.goLineUp = _.noop;
        CodeMirror.commands.goLineDown = _.noop;
        CodeMirror.commands.newlineAndIndent = _.noop;
      })
      .on('hidden.atwho', function () {
        CodeMirror.commands.goLineUp = codeMirrorGoLineUp;
        CodeMirror.commands.goLineDown = codeMirrorGoLineDown;
        CodeMirror.commands.newlineAndIndent = codeMirrorNewlineAndIndent;
      });
      // END at.js 配置
    });
    // END 编辑器相关
    // 评论回复
    $('#content').on('click', '.reply2_btn', function (event) {
      var $btn = $(event.currentTarget);
      var parent = $btn.closest('.reply_area');
      var editorWrap = parent.find('.reply2_form');
      parent.find('.reply2_area').prepend(editorWrap);
      var textarea = editorWrap.find('textarea.editor');
      var user = $btn.closest('.author_content').find('.reply_author').text().trim();
      if (user.indexOf("(") > -1 && user.indexOf(")") > user.indexOf("(")){
          user = user.substr(user.indexOf("(")+1, user.indexOf(")") - user.indexOf("(") - 1);
      }
      var editor = textarea.data('editor');
      editorWrap.show('fast', function () {
        var cm = editor.codemirror;
        cm.focus();
        if(cm.getValue().indexOf('@' + user) < 0){
          editor.push('@' + user + ' ');
        }
      });
    });
    $('#content').on('click', '.reply2_at_btn', function (event) {
      var $btn = $(event.currentTarget);
      var editorWrap = $btn.closest('.reply2_area').find('.reply2_form');
      $btn.closest('.reply2_item').after(editorWrap);
      var textarea = editorWrap.find('textarea.editor');
      var user = $btn.closest('.reply2_item').find('.reply_author').text().trim();
      var editor = textarea.data('editor');
      editorWrap.show('fast', function () {
        var cm = editor.codemirror;
        cm.focus();
        if(cm.getValue().indexOf('@' + user) < 0){
          editor.push('@' + user + ' ');
        }
      });
    });
    // END 评论回复
    // 加入收藏
    $('#collect_btn').click(function () {
      var $me = $(this);
      var action = $me.attr('action');
      var data = {
        topic_id: '${obj.topic.id}',
        _csrf: '${obj._csrf}'
      };
      var $countSpan = $('.collect-topic-count');
      $.post('/topic/' + action, data, function (data) {
        if (data.status === 'success') {
          if (action == 'collect') {
            $me.text('取消收藏');
            $me.attr('action', 'de_collect');
          } else {
            $me.text('加入收藏');
            $me.attr('action', 'collect');
          }
          $me.toggleClass('span-success');
        }
      }, 'json');
    });
    // END 加入收藏
    // 删除回复
    $('#content').on('click', '.delete_reply_btn, .delete_reply2_btn', function (event) {
      var $me = $(event.currentTarget);
      if (confirm('确定要删除此回复吗？')) {
        var reply_id = null;
        if ($me.hasClass('delete_reply_btn')) {
          reply_id = $me.closest('.reply_item').attr('reply_id');
        }
        if ($me.hasClass('delete_reply2_btn')) {
          reply_id = $me.closest('.reply2_item').attr('reply_id');
        }
        var data = {
          reply_id: reply_id,
          _csrf: "${obj._csrf}"
        };
        $.post('/reply/' + reply_id + '/delete', data, function (data) {
          if (data.status === 'success') {
            if ($me.hasClass('delete_reply_btn')) {
              $me.closest('.reply_item').remove();
            }
            if ($me.hasClass('delete_reply2_btn')) {
              $me.closest('.reply2_item').remove();
            }
          }
        }, 'json');
      }
      return false;
    });
    // END 删除回复
    // 删除话题
    $('.delete_topic_btn').click(function () {
      var topicId = $(this).data('id');
      if (topicId && confirm('确定要删除此话题吗？')) {
        $.post('/topic/' + topicId + '/delete', { _csrf: $('#_csrf').val() }, function (result) {
          if (!result.success) {
            alert(result.message);
          } else {
            location.href = '/';
          }
        });
      }
      return false;
    });
    // END 删除话题
    // 用户 hover 在回复框时才显示点赞按钮
    $('.reply_area').hover(
      function () {
        $(this).find('.up_btn').removeClass('invisible');
      },
      function () {
        var $this = $(this);
        if ($this.find('.up-count').text().trim() === '') {
          $this.find('.up_btn').addClass('invisible');
        }
      });
    // END 用户 hover 在回复框时才显示点赞按钮
    
    // 提交回复
    $('#reply_form').on('submit', function (e) {
    	if (console) 
    		console.log($(this).serialize());
    	$.ajax({
    		url : "${ctxPath}/yvr/t/${obj.topic.id}/reply",
    		method : "POST",
    		data : $(this).serialize(),
    		dataType : "json",
    		success : function(re) {
    			if (re.ok) {
    				location.reload();
    			} else {
    				$('#reply_form').button('reset');
    				layer.alert(re.msg);
    			}
    		}
    	});
    	return false;
    });
    $('.reply2_area').on('submit', function (event) {
    	var $btn = $(event.currentTarget);
      	var editorWrap = $btn.closest('.reply2_area').find('.reply2_form');
    	if (console) 
    		console.log($(editorWrap).serialize());
    	$.ajax({
    		url : "${ctxPath}/yvr/t/${obj.topic.id}/reply",
    		method : "POST",
    		data : $(editorWrap).serialize(),
    		dataType : "json",
    		success : function(re) {
    			if (re.ok) {
    				location.reload();
    			} else {
    				layer.alert(re.msg);
    				$('.reply2_area').button('reset');
    			}
    		}
    	});
    	return false;
    });
  });
</script>

<!--#} #-->
<script type="text/javascript">
  (function(){
    var timer = null; //对话框延时定时器
    // 初始化 $('.replies_history')
    var $repliesHistory = $('.replies_history');
    var $repliesHistoryContent = $repliesHistory.find('.inner_content');
    $repliesHistory.hide();
    // END
    // 鼠标移入对话框清除隐藏定时器；移出时隐藏对话框
    $repliesHistory.on('mouseenter', function(){
      clearTimeout(timer);
    }).on('mouseleave', function(){
      $repliesHistory.fadeOut('fast');
    });
    // 显示被 at 用户的本页评论
    if ($('.reply2_item').length === 0) {
      // 只在流式评论布局中使用
      $('#content').on('mouseenter', '.reply_content a', function (e) {
        clearTimeout(timer);
        var $this = $(this);
        if ($this.text()[0] === '@') {
          var thisText = $this.text().trim();
          var loginname = thisText.slice(1);
          var offset = $this.offset();
          var width = $this.width();
          var mainOffset = $('#main').offset();
          $repliesHistory.css('left', offset.left-mainOffset.left+width+10); // magic number
          $repliesHistory.css('top', offset.top-mainOffset.top-10); // magic number
          $repliesHistory.css({
            'z-index': 1,
          });
          $repliesHistoryContent.empty();
          var chats = [];
          var replyToId = $this.closest('.reply_item').attr('reply_to_id');
          while (replyToId) {
            var $replyItem = $('.reply_item[reply_id=' + replyToId + ']');
            var replyContent = $replyItem.find('.reply_content').text().trim();
            if (replyContent.length > 0) {
              chats.push([
                $($replyItem.find('.user_avatar').html()).attr({
                  height: '30px',
                  width: '30px',
                }), // avatar
                (replyContent.length>300?replyContent.substr(0,300)+'...':replyContent), // reply content
                '<a href="#'+replyToId+'" class="scroll_to_original" title="查看原文">↑</a>'
              ]);
            }
            replyToId = $replyItem.attr('reply_to_id');
          }
          if(chats.length > 0) {
            chats.reverse();
            $repliesHistoryContent.append('<div class="title">查看对话</div>');
            chats.forEach(function (pair, idx) {
              var $chat = $repliesHistoryContent.append('<div class="item"></div>');
              $chat.append(pair[0]); // 头像
              $chat.append($('<span>').text(pair[1])); // 内容
              $chat.append(pair[2]); // 查看原文 anchor
            });
            $repliesHistory.fadeIn('fast');
          }else{
            $repliesHistory.hide();
          }
        }
      }).on('mouseleave', '.reply_content a', function (e) {
        timer = setTimeout(function(){
          $repliesHistory.fadeOut('fast');
        }, 500);
      });
    }
    // END 显示被 at 用户的本页评论
  })();
  // 点赞
  $('.up_btn').click(function (e) {
    var $this = $(this);
    var replyId = $this.closest('.reply_area').attr('reply_id');
    $.ajax({
      url: '${ctxPath}/yvr/t/${obj.topic.id}/reply/' + replyId + '/up',
      method: 'POST',
      dataType : "json"
    }).done(function (data) {
      if (data.ok) {
        $this.removeClass('invisible');
        var currentCount = Number($this.next('.up-count').text().trim()) || 0;
        if (data.data === 'up') {
          $this.next('.up-count').text(currentCount + 1);
          $this.addClass('uped');
        } else {
          if (data.data === 'down') {
            $this.next('.up-count').text(currentCount - 1);
            $this.removeClass('uped');
          }
        }
      } else {
        layer.alert(data.msg);
      }
    }).fail(function (xhr) {
      if (xhr.status === 403) {
        alert('请先登录，登陆后即可点赞。');
      }
    });
  });
  // END 点赞
</script>

<!--#}  #-->

<script>
var QueryString = function () {
  // This function is anonymous, is executed immediately and 
  // the return value is assigned to QueryString!
  var query_string = {};
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
        // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
      query_string[pair[0]] = decodeURIComponent(pair[1]);
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
      query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
      query_string[pair[0]].push(decodeURIComponent(pair[1]));
    }
  } 
    return query_string;
}();
function send_to_phone() {
	$.ajax({
		url : "${base}/yvr/t/${obj.topic.id}/push",
		method : "POST",
		success : function(){
			layer.alert("已推送到手机");
		},
		fail : function() {
			layer.alert("服务器走神了");
		},
		error : function() {
			layer.alert("服务器走神了");
		}
	});
}
$(function() {
	prettyPrint();
	$("#copy_link_btn").zclip({
		copy:function() {
			return "${obj.topic.title} " + location.href;
		},
		path : '${cdnbase}${base}/rs/js/ZeroClipboard.swf'
	});
	$("#TopicTagSpan").editInPlace({
		method : "POST",
    	url: "${base}/yvr/admin/update/tags",
    	textarea_rows : 5,
    	text_size:100,
		bg_over: "none",
		bg_out: "none",
    	field_type: "textarea",
		value_required: "true",
		params : "id=${obj.topic.id}",
		success: function(data){
			location.reload();
		},
		error: function(e){
			layer.alert("当前仅管理员可以修改");
		}
	});
});

	
	
	function topic_update(tid, val, tp) {
		var param = {id:tid, "opt":tp};
		param[tp] = val;
		$.ajax({
			method:"POST",
			url : "${base}/yvr/admin/update",
			data : param,
			dataType : "json",
			success : function(data) {
				location.reload();
			}
		});
	};
</script>
